<!DOCTYPE html>
<html>
<head>
	<title>demo animate</title>
	<style type="text/css">
		.ball {
			width: 40px;
			height: 40px;
			border-radius: 20px;
		}
		.ball1{
			background:red;
		}
		.ball2{
			background:yellow;
		}
		.ball3{
			background:green;
		}
	</style>
</head>
<script type="text/javascript" src="./node_modules/bluebird/js/browser/bluebird.js"></script>
<body>
	<div class="ball ball1" style="margin-left: 0;"></div>
	<div class="ball ball2" style="margin-left: 0;"></div>
	<div class="ball ball3" style="margin-left: 0;"></div>
	<script type="text/javascript">
		var b1 = document.querySelector('.ball1');
		var b2 = document.querySelector('.ball2');
		var b3 = document.querySelector('.ball3');

    //1秒60帧，存在误差

	/*animate(b1, 100, function() {
		animate(b2, 200, function() {
			animate(b3, 300, function() {
				animate(ba3, 150, function() {
					animate(b2, 150, function() {
						animate(b1, 150, function() {
							//
						});
					});
				});
			});
		});
	});*/

	var Promise = window.Promise

	function promiseAnimate(ball,distance) {
		return new Promise(function(resolve,reject) {

			//下划线_animate加下划线表示是个私有函数
			function _animate(ball,distance,cb) {
				setTimeout(function() {
					var mleft = parseInt(ball.style.marginLeft, 10);		
					if(mleft === distance){
						resolve();
					}else{
						if(mleft < distance){
							mleft++;
						}else{
							mleft--;
						}
						ball.style.marginLeft = mleft + 'px';
						_animate(ball,distance);
					}
				}, 13);
			};
			_animate(ball,distance);

		})
	}

	promiseAnimate(b1, 100)
		.then(function() {
			return promiseAnimate(b2,200)
		})	
		.then(function() {
			return promiseAnimate(b3,300)
		})
		.then(function() {
			return promiseAnimate(b3,150)
		})
		.then(function() {
			return promiseAnimate(b2,150)
		})
		.then(function() {
			return promiseAnimate(b1,150)
		})

</script>
</body>

</html>